package com.lovo.J177.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lovo.J177.model.dos.SStudentDO;
import com.lovo.J177.dao.SStudentDAO;
import com.lovo.J177.model.dto.SStudentDTO;
import com.lovo.J177.service.SStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lovo.J177.util.RedisUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bdk
 * @since 2020-11-24
 */
@Service
public class SStudentServiceImpl extends ServiceImpl<SStudentDAO, SStudentDO> implements SStudentService {
    @Resource
    private SStudentDAO sStudentDAO;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public IPage<SStudentDO> selectPageExt( int page, int size) {
        Page pageObj = null;
        // 判断缓冲中是否存在查询的学生信息
        pageObj = (Page) redisUtil.get("selectAll="+page+"="+size);
        if (pageObj == null) {
            pageObj = new Page(page,size);
            List list = sStudentDAO.selectPageExt(pageObj);
            pageObj.setRecords(list);
            redisUtil.set("selectAll="+page+"="+size,pageObj);
        }

        return pageObj;
    }

    @Override
    public void saveStudent(SStudentDTO sStudentDTO) {
        SStudentDO studentDO = new SStudentDO();
        BeanUtils.copyProperties(sStudentDTO,studentDO);
        studentDO.setPkSid(redisUtil.generateOrderId());
        sStudentDAO.insert(studentDO);
        redisUtil.del("selectAll=1=4");
        redisUtil.del("selectAll=2=4");
    }

    @Override
    public SStudentDO findById(String id) {
        SStudentDO sStudentDO=null;
         sStudentDO =(SStudentDO)redisUtil.get("selectById="+id);
        if(sStudentDO==null){
            sStudentDO= sStudentDAO.findByPkid(id);
            redisUtil.set("selectById="+id,sStudentDO);
            redisUtil.del("selectAll=1=4");
        }
        return sStudentDO;
    }

    @Override
    public void updateStudent(SStudentDTO sStudentDTO) {
        SStudentDO studentDO = new SStudentDO();
        BeanUtils.copyProperties(sStudentDTO,studentDO);
        sStudentDAO.updateByPkId(studentDO);
        SStudentDO studentDO1 = null;
        studentDO1 = (SStudentDO ) redisUtil.get("selectById="+studentDO.getPkSid());

        if(studentDO1==null){
            redisUtil.del("selectById="+studentDO.getPkSid());
        }
        redisUtil.del("selectAll=1=4");
        redisUtil.del("selectAll=2=4");
    }

    @Override
    public void del(String id) {
        sStudentDAO.deleteById(id);
        redisUtil.del("selectById="+id);

        for(int i=1;i<5;i++){
            redisUtil.del("selectAll="+i+"=4");
        }

    }
}
